#include <iostream>
using namespace std;
#include <sqlite3.h>

#include <unistd.h>
#include <iomanip>
#include <vector>
void excute(sqlite3 * myDB)
{   
    //创建数据库表
    const char *sql = "create table if not exists userInfo(username text not null,passwd text not null);";

    //执行sql语句
    int ret = sqlite3_exec(myDB,sql,NULL,NULL,NULL);
    if(ret != SQLITE_OK)
    {
        cout<<"sqlite3 open error"<<sqlite3_errmsg(myDB)<<endl;
        _exit(-1);
    }
    // std::cout<<"请输入你的名字"<<std::endl;
    // string username;
    // cin >> username;
    // std::cout<<"请输入你的密码"<<std::endl;
    // string passwd ;
    // cin >> passwd;
// #if 1
//     char buffer[64] = "insert into userInfo (username,passwd) values ('%s','%s');";

//     char requestSql[128] = {0};
//     sprintf(requestSql,buffer,username.c_str(),passwd.c_str());
// #endif
//     ret = sqlite3_exec(myDB,requestSql,NULL,NULL,NULL);
//     if(ret != SQLITE_OK)
//     {
//         cout<<"sqlite3 open error"<<sqlite3_errmsg(myDB)<<endl;
//         _exit(-1);
//     }

    const char *sql3 = "update userInfo set passwd = '123456' where username = 'zhangsan';";

    // char requestSql2[128] = {0};
    // sprintf(requestSql2,buffer2,username.c_str(),passwd.c_str());
    ret = sqlite3_exec(myDB,sql3,NULL,NULL,NULL);
    if(ret != SQLITE_OK)
    {
        cout<<"sqlite3 open error"<<sqlite3_errmsg(myDB)<<endl;
        _exit(-1);
    }
}   
int main()
{   
    sqlite3 * myDB = NULL;
    const char * baseName = "./test2.db";

    //连接数据库
    int ret = sqlite3_open(baseName,&myDB);
    if(ret != SQLITE_OK)
    {
        cout<<"sqlite3 open error"<<sqlite3_errmsg(myDB)<<endl;
        _exit(-1);
    }
    
    
    const char *sql = "select *from userInfo;";
    char **result = NULL;
    int rows = 0;
    int columns = 0;
    sqlite3_get_table(myDB,sql,&result,&rows,&columns,NULL);
    if(ret != SQLITE_OK)
    {
        cout<<"sqlite3_get_table error:"<<sqlite3_errmsg(myDB)<<endl;
        exit(-1);
    }
    
    vector<vector<string>> Datas;
    cout<<"row:"<<rows<<"col:"<<columns<<endl;
    for(int row = 1;row <= rows;row++)
    {   
        vector<string> rowData;
        for(int col = 0;col < columns;col++)
        {
            // cout <<left<<setw(16)<<result[row*columns + col];
            rowData.push_back(result[row*columns+col]);
        }
        Datas.push_back(rowData);
    }
    cout<<endl;

    cout << "rows:" <<Datas.size()<<endl;
    
    for(int idx = 0;idx < Datas.size();idx++)
    {
        vector<string> rowData = Datas[idx];
        for(int jdx = 0;jdx < rowData.size();jdx++)
        {
            cout<<"rowData[" << jdx << "]="<<rowData[jdx] << "\t";
        }
        cout<<endl;
    }
    // 关闭数据库
    sqlite3_close(myDB);
    return 0;
}